package com.ruoyi.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.erp.domain.SysBizSerial;
import com.ruoyi.erp.domain.bo.SysBizSerialBo;
import com.ruoyi.erp.domain.vo.SysBizSerialVo;
import com.ruoyi.erp.mapper.SysBizSerialMapper;
import com.ruoyi.erp.service.ISysBizSerialService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.List;

/**
 * 流水号Service业务层处理
 *
 * @author chenyun
 * @date 2022-03-13
 */
@Service
public class SysBizSerialServiceImpl extends ServicePlusImpl<SysBizSerialMapper, SysBizSerial, SysBizSerialVo> implements ISysBizSerialService {
    private static final String LOCK_KEY = "SysBizSerial";

    @Override
    public SysBizSerialVo queryById(Long id){
        return getVoById(id);
    }

    @Override
    public TableDataInfo<SysBizSerialVo> queryPageList(SysBizSerialBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysBizSerial> lqw = buildQueryWrapper(bo);
        Page<SysBizSerialVo> result = pageVo(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<SysBizSerialVo> queryList(SysBizSerialBo bo) {
        LambdaQueryWrapper<SysBizSerial> lqw = buildQueryWrapper(bo);
        return listVo(lqw);
    }

    @Override
    public Boolean insertByBo(SysBizSerialBo bo) throws Exception{
        SysBizSerial add = BeanUtil.toBean(bo, SysBizSerial.class);
        validEntityBeforeSave(add);
        QueryWrapper wrapper = existQueryWrapper(add);
        boolean flag = insertIdempotency(add,LOCK_KEY,wrapper,getMsg(add));
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(SysBizSerialBo bo) throws Exception{
        SysBizSerial update = BeanUtil.toBean(bo, SysBizSerial.class);
        validEntityBeforeSave(update);
        QueryWrapper wrapper = existQueryWrapper(update);
        boolean flag = updateIdempotency(update,LOCK_KEY,wrapper,getMsg(update));
        return flag;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysBizSerial entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    @Lock4j(name = "getSerialNum")
    public Long getSerialNum(@Validated @NotNull Long orgId,@NotNull String bizId, Long initNum,@NotNull Integer year,@NotNull Integer period, Integer count) {
        QueryWrapper<SysBizSerial> query = new QueryWrapper();
        query.eq("org_id" , orgId);
        query.eq("biz_id" , bizId);
        query.eq(ObjectUtil.isNotNull(year),"year" , year);
        query.eq(ObjectUtil.isNotNull(period),"period" , period);
        query.orderBy( true,true,"base_num");
        List<SysBizSerial> list = list(query);

        if (count==null || count<1){
            count = 1;
        }
        Long num = null;
        if (CollUtil.isNotEmpty(list) && list.size()>=1){
            // 如果取多个流水号，取最大号及其连号
            SysBizSerial entity;
            if (count>1){
                entity = list.get(list.size()-1);
            }else {
                entity = list.get(0);
            }
            Long baseNum = entity.getBaseNum() ==null ? 0 : entity.getBaseNum();
            entity.setBaseNum(baseNum+count);
            num = baseNum;
            updateById(entity);
        } else {
            SysBizSerial entity = new SysBizSerial();
            entity.setOrgId(orgId);
            entity.setBizId(bizId);
            entity.setYear(year);
            entity.setPeriod(period);
            // 默认从1开始
            Long baseNum = 1L;
            if(initNum > 0){
               baseNum = initNum;
            }
            entity.setBaseNum(baseNum);
            num = baseNum;
            save(entity);
        }
        return num;
    }

    @Override
    @Lock4j(name = "cancelSerialNum")
    public void cancelSerialNum(Long orgId, String bizId, Long baseNum, Integer year, Integer period, Integer count) {
        // 回收的流水号，插入到流水表，等待下次使用
        if (count==null || count<1){
            count = 1;
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("org_id",orgId);
        wrapper.eq("biz_id",bizId);
        wrapper.eq("year",year);
        wrapper.eq("period",period);
        if (count==1){
            SysBizSerial entity = new SysBizSerial();
            entity.setOrgId(orgId);
            entity.setBizId(bizId);
            entity.setYear(year);
            entity.setPeriod(period);
            entity.setBaseNum(baseNum);

            wrapper.eq("base_num",baseNum);
            if (count(wrapper)==0){
                save(entity);
            }
        } else {
            List<SysBizSerial> list = CollUtil.newArrayList();
            for(int i = 0; i<count ; i++){
                SysBizSerial entity = new SysBizSerial();
                entity.setOrgId(orgId);
                entity.setBizId(bizId);
                entity.setYear(year);
                entity.setPeriod(period);
                entity.setBaseNum(baseNum-i);

                wrapper.eq("base_num",baseNum-i);
                if (count(wrapper)==0){
                    list.add(entity);
                }
            }
            if (list.size()>0){
                saveBatch(list,1000);
            }
        }

    }

    /**
     * 唯一判断查询条件，暂支持一个键
     * @param entity
     * @return
     */
    private QueryWrapper<SysBizSerial> existQueryWrapper(SysBizSerial entity) {
        return null;
    }

    private String getMsg(SysBizSerial entity){
            return null;
    }
}
